package examples

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 启动服务
func DefaultStart() {
	router := gin.Default()

	// 注册接口
	AsciiJson(router)
	PingTest(router)
	SecureJson(router)
	Cookie(router)
	SingleUpload(router)
	MultipleUpload(router)

	// route.Run(":8088") 等同如下：
	// 方式一：router.ListenAndServe(":8080", router)
	// 方式二:
	server := &http.Server{
		Addr:    ":8080",
		Handler: router,
		// ReadTimeout:    10 * time.Second,
		// WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	server.ListenAndServe()
}

// 将内容转用 Ascii码 表示
func AsciiJson(r *gin.Engine) {
	r.GET("/someJson", func(ctx *gin.Context) {
		data := map[string]interface{}{
			"lang": "go 语言",
			"tag":  "<br/>",
		}

		ctx.AsciiJSON(http.StatusOK, data)
	})
}

// 测试 ping
func PingTest(router *gin.Engine) {
	router.GET("ping", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})
}

func SecureJson(router *gin.Engine) {
	router.GET("/someJSON2", func(c *gin.Context) {
		names := []string{"lena", "austin", "foo"}
		// Will output  :   while(1);["lena","austin","foo"]
		c.SecureJSON(http.StatusOK, names)
	})
}

// 获取 header中 Cookie 信息
func Cookie(router *gin.Engine) {
	router.GET("/cookie", func(c *gin.Context) {
		cookie, err := c.Cookie("gin_cookie")

		// 当 cookie 不存在时，则报错 err 不为空
		if err != nil {
			fmt.Printf("cookie: %v\n", cookie)
			cookie = "NotSet"
			c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
		}

		fmt.Printf("Cookie value: %s \n", cookie)
	})
}

// 单文件上传
func SingleUpload(router *gin.Engine) {
	// Set a lower memory limit for multipart forms (default is 32 MiB)
	router.MaxMultipartMemory = 8 << 20 // 8 MiB
	router.POST("/upload", func(c *gin.Context) {
		// single file
		file, _ := c.FormFile("file")
		log.Println(file.Filename)

		// Upload the file to specific dst.
		// c.SaveUploadedFile(file, dst)

		c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
	})
}

// 多文件上传
func MultipleUpload(router *gin.Engine) {
	// Set a lower memory limit for multipart forms (default is 32 MiB)
	router.MaxMultipartMemory = 8 << 20 // 8 MiB
	router.POST("/uploads", func(c *gin.Context) {
		// Multipart form
		form, _ := c.MultipartForm()
		// form-data中参数名为 files
		files := form.File["files"]

		for _, file := range files {
			fmt.Println(file.Filename)

			// Upload the file to specific dst.
			// c.SaveUploadedFile(file, dst)
		}
		c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
	})
}
